<template>
  <div>
    <el-dialog
      class="custom-dialog"
      v-model="dialogVisible"
      :title="title"
      width="500px"
      @close="handleClose"
    >
      <el-form
        class="data-form"
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="140px"
      >
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="所在园区" prop="parkId">
              <el-select
                class="data-input"
                v-model="form.parkId"
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="(item, index) of parkOptions"
                  :key="index"
                  :label="item.name"
                  :value="item.pkid"
                  :disabled="item.enable === '0'"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="承租类型" prop="type">
              <el-radio-group v-model="form.type">
                <el-radio
                  v-for="(item, index) of dictOptions['tenantType']"
                  :key="index"
                  :value="item.value"
                  >{{ item.name }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="form.type">
            <el-form-item
              :label="`承租${getDictValue('tenantType', form.type)}名称`"
              prop="name"
            >
              <el-input
                class="data-input"
                v-model="form.name"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col
            :span="24"
            v-if="
              ['企业', '政府'].includes(getDictValue('tenantType', form.type))
            "
          >
            <el-form-item
              label="统一社会信用代码"
              prop="code"
              :rules="rules.code1"
            >
              <el-input
                class="data-input"
                v-model="form.code"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col
            :span="24"
            v-if="['个人'].includes(getDictValue('tenantType', form.type))"
          >
            <el-form-item label="身份证号码" prop="code" :rules="rules.code2">
              <el-input
                class="data-input"
                v-model="form.code"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="负责人">
              <el-input
                class="data-input"
                v-model="form.dutyPerson"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="经营范围">
              <el-input
                class="data-input"
                v-model="form.businessScope"
                placeholder="请输入"
                type="textarea"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                class="data-input"
                v-model="form.remark"
                placeholder="请输入"
                type="textarea"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="附件资料">
              <VUpload width="250" v-model="form.files" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="handleClose(false)" :loading="loading"
          >取消</el-button
        >
        <el-button type="primary" @click="handleSubmit" :loading="loading"
          >确定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { cardId } from '@/utils/validate'
import { useDict } from '@/hooks/useDict'
const { dictOptions, initListDictOptions, getDictValue } = useDict()
import VUpload from '@/components/upload/index.vue'
import {
  tenantAdd,
  tenantUpdate,
  tenantDetail,
} from '@/api/manager/dataManage/tenant'
import { parkPageList } from '@/api/manager/dataManage/park'
defineOptions({
  name: 'AddDialog',
})
const props = defineProps({
  detail: {
    type: Object,
  },
})
watch(
  () => props.detail,
  async () => {
    if (props.detail.pkid && dialogVisible.value) {
      handleDetail()
    } else {
      if (props.detail.parkId) {
        form.value.parkId = props.detail.parkId
      } else {
        form.value = { files: [] }
      }
    }
  },
)
const handleDetail = async () => {
  const res = await tenantDetail({ pkid: props.detail.pkid })
  if (res.success) {
    // 处理附件资料
    res.data.files = res.data.fileList || []
    delete res.data.fileList
    form.value = { ...res.data }
  } else {
    ElMessage.error(res.message)
  }
}
const emit = defineEmits(['close'])
const title = ref('')
const dialogVisible = ref(false)
const handleClose = (isFlash) => {
  form.value = { files: [] }
  formRef.value.clearValidate()
  dialogVisible.value = false
  emit('close', isFlash)
}
const formRef = ref(null)
const form = ref({
  files: [],
})
const validateIdCard = (rule, value, callback) => {
  if (!value) {
    callback()
  } else {
    const list = cardId(value)
    if (value && list[0]) {
      callback(new Error(list[1]))
    } else {
      callback()
    }
  }
}
const rules = ref({
  parkId: [{ required: true, message: '请选择所在园区', trigger: 'blur' }],
  type: [{ required: true, message: '请选择承租类型', trigger: 'blur' }],
  name: [{ required: true, message: '请输入承租主体名称', trigger: 'blur' }],
  code1: [
    {
      required: true,
      message: '请输入统一社会信用代码',
      trigger: 'blur',
    },
    {
      message: '请输入15或18位统一社会信用代码',
      pattern:
        /^([0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}|[1-9]\d{14})$/,
      trigger: 'blur',
    },
  ],
  code2: [
    {
      required: true,
      message: '请输入身份证号码',
      trigger: 'blur',
    },
    {
      validator: validateIdCard,
    },
  ],
})

const loading = ref(false)
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      loading.value = true
      const params = JSON.parse(JSON.stringify(form.value))
      // 处理附件资料
      if (params.files && params.files.length > 0) {
        params.files = params.files
          .map((i) => {
            return i.pkid
          })
          .join(',')
      } else {
        params.files = ''
      }
      try {
        let res
        if (form.value.pkid) {
          res = await tenantUpdate(params)
        } else {
          res = await tenantAdd(params)
        }
        if (res.success) {
          ElMessage.success('保存成功')
          handleClose(true)
        } else {
          ElMessage.error(res.message)
        }
        loading.value = false
      } catch (error) {
        console.log('error', error)
        loading.value = false
      }
    } else {
      ElMessage.warning('请正确录入信息')
    }
  })
}
const parkOptions = ref([])
const initParkList = async () => {
  const res = await parkPageList({ pageIndex: 1, pageSize: 9999 })
  parkOptions.value = res.data.list
}
defineExpose({ dialogVisible, title })
onMounted(() => {
  initListDictOptions(['tenantType'])
  initParkList()
})
</script>
<style lang="scss" scoped></style>
